package 康复训练_JavaGo并驾齐驱;

public class Jz53I在排序数组中查找数字 {

    /**
     * 统计一个数字在排序数组中出现的次数。
     */

    public int search(int[] nums, int target) {
        int index = binarySearch(nums, target);
        if (index == -1) {
            return 0;
        }
        int result = 1;
        int leftIndex = index - 1;
        while (leftIndex >= 0 && nums[leftIndex] == target) {
            leftIndex--;
            result++;
        }
        int rightIndex = index + 1;
        while (rightIndex < nums.length && nums[rightIndex] == target) {
            rightIndex++;
            result++;
        }
        return result;
    }

    private int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int midIndex = (right - left) / 2 + left;
            int midNum = nums[midIndex];
            if (midNum > target) {
                right = midIndex - 1;
            } else if(midNum < target) {
                left = midIndex + 1;
            } else {
                return midIndex;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Jz53I在排序数组中查找数字 n = new Jz53I在排序数组中查找数字();
        int[] arr = {5,7,7,8,8,10};
        int index = n.binarySearch(arr, 6);
        System.out.println(index);
    }

}
